﻿using Modbus.Messages;

namespace Modbus
{
	partial class ModbusClient
	{
		public void WriteSingleRegister(byte slaveAddress, int registerAddress, short registerValue)
		{
			//
			// Input arguments validation.
			//

			Ensure.ArgumentInRange(SR.Argument_registerAddress, registerAddress, MinDataAddress, MaxDataAddress);

			//
			// Internal state validation.
			//

			this.ThrowIfDisposed();

			//
			// Request creation.
			//

			WriteSingleRegisterMessage request = new WriteSingleRegisterMessage();

			request.FunctionCode = FunctionCodes.WriteSingleRegister;
			request.RegisterAddress = (ushort)(registerAddress);
			request.RegisterValue = registerValue;

			//
			// Perform transaction.
			//

			if (slaveAddress == BroadcastAddress)
			{
				this.transport.Request(slaveAddress, request);
			}
			else
			{
				var response = this.transport.Request<WriteSingleRegisterMessage>(slaveAddress, request);

				//
				// Response validation.
				//
				
				if (response.RegisterAddress != request.RegisterAddress)
				{
					throw new MismatchResponseException(SR.ModbusMessageField_RegisterAddress);
				}
				if (response.RegisterValue != request.RegisterValue)
				{
					throw new MismatchResponseException(SR.ModbusMessageField_RegisterValue);
				}
			}
		}
	}
}
